package fr.vod.threads;

import fr.vod.net.Receiver;
import fr.vod.net.ReceiverMulticast;
import fr.vod.net.Sender;
import fr.vod.net.SenderMulticast;

public class CommandThread extends Thread {

	private boolean end = false;
	private Receiver r;
	private boolean isInit = false;
	private int fileSize = 0;
	private String cmd;
	private String reponse;
	private Sender s;
	private boolean eof = false;
	private String cmdend;

	public CommandThread(ReceiverMulticast r, SenderMulticast s, String cmd, String reponse,
			String cmdend) {
		this.r = r;
		this.cmd = cmd;
		this.s = s;
		this.reponse = reponse;
		this.cmdend = cmdend;

	}

	public void run() {
		String msg = "";
		while (!end) {
			try {
				msg = r.receive();
				if (msg.startsWith(cmd)) {
					try {
						if (!isInit) {
							fileSize = Integer.valueOf(msg.substring(cmd
									.length()));
							isInit = true;
						} else if (fileSize != Integer.valueOf(msg
								.substring(cmd.length()))) {
							s.send("NOT_SAME_FILE");
						}
						s.send(reponse);
					} catch (NumberFormatException e) {
						s.send("ERROR_FILE_SIZE");
					}

				} else if (msg.equalsIgnoreCase(cmdend)) {
					eof = true;
				}

			} catch (Exception e) {
				end = true;
			}
		}
	}

	public void end() {
		end = true;
	}

	public boolean getIsInit() {
		return isInit;
	}

	public int getFileSize() {
		return fileSize;

	}

	public boolean getEof() {
		return eof;
	}

	/**
	 * 
	 * @param msg
	 * @throws Exception
	 */
	public void send(String msg) throws Exception {
		s.send(msg);
	}
}
